package com.example.wechat;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.example.wechat.fragment.ChatFragment;
import com.example.wechat.fragment.ContactFragment;
import com.example.wechat.fragment.DiscoverFragment;
import com.example.wechat.fragment.MeFragment;

public class MainActivity extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private Fragment chatFragment;
    private Fragment contactFragment;
    private Fragment discoverFragment;
    private Fragment meFragment;
    private Fragment currentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        initFragments();
        initBottomNavigation();
    }

    private void initFragments() {
        chatFragment = new ChatFragment();
        contactFragment = new ContactFragment();
        discoverFragment = new DiscoverFragment();
        meFragment = new MeFragment();

        // 默认显示聊天界面
        fragmentManager.beginTransaction()
                .add(R.id.fragment_container, chatFragment)
                .commit();
        currentFragment = chatFragment;
    }

    private void initBottomNavigation() {
        BottomNavigationView bottomNavigation = findViewById(R.id.bottom_navigation);
        bottomNavigation.setSelectedItemId(R.id.navigation_chat);
        bottomNavigation.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.navigation_chat) {
                switchFragment(chatFragment);
                return true;
            } else if (itemId == R.id.navigation_contact) {
                switchFragment(contactFragment);
                return true;
            } else if (itemId == R.id.navigation_discover) {
                switchFragment(discoverFragment);
                return true;
            } else if (itemId == R.id.navigation_me) {
                switchFragment(meFragment);
                return true;
            }
            return false;
        });
    }

    private void switchFragment(Fragment targetFragment) {
        if (currentFragment != targetFragment) {
            if (!targetFragment.isAdded()) {
                fragmentManager.beginTransaction()
                        .hide(currentFragment)
                        .add(R.id.fragment_container, targetFragment)
                        .commit();
            } else {
                fragmentManager.beginTransaction()
                        .hide(currentFragment)
                        .show(targetFragment)
                        .commit();
            }
            currentFragment = targetFragment;
        }
    }
} 